package com.huiminpay.transaction.controller;

import com.alibaba.fastjson.JSON;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.EncryptUtil;
import com.huiminpay.common.cache.util.IPUtil;
import com.huiminpay.common.cache.util.ParseURLPairUtil;
import com.huiminpay.merchant.api.AppService;
import com.huiminpay.paymentagent.dto.PaymentResponseDTO;
import com.huiminpay.transaction.api.TransactionService;
import com.huiminpay.transaction.common.util.BrowserType;
import com.huiminpay.transaction.convert.PayOrderConvert;
import com.huiminpay.transaction.dto.PayOrderDTO;
import com.huiminpay.transaction.entity.PayOrder;
import com.huiminpay.transaction.vo.OrderConfirmVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Controller
public class PayController {
    @Resource
    TransactionService transactionService;

    @Reference
    AppService appService;

    /**
     * 支付入口
     *
     * @param ticket
     * @param request
     * @return
     */
    @RequestMapping(value = "/pay-entry/{ticket}")
    public String payEntry(@PathVariable("ticket") String ticket, HttpServletRequest request) {
        //解析ticket
        //解码
        String decodeUTF8StringBase64 = EncryptUtil.decodeUTF8StringBase64(ticket);
        //转为对象
        PayOrder payOrder = JSON.parseObject(decodeUTF8StringBase64, PayOrder.class);

        //将对象转换为url格式
        String param;
        try {
            param = ParseURLPairUtil.parseURLPair(payOrder);
        } catch (Exception e) {
            throw new BusinessException(CommonErrorCode.E_88889);
        }

        //根据不同的客户端，判断支付类型，跳转到不同的资源页面
        String header = request.getHeader("User-Agent");
        BrowserType browserType = BrowserType.valueOfUserAgent(header);
        switch (browserType) {
            case ALIPAY:
                return "forward:/pay-page?" + param;
            case WECHAT:
                return "forward:/pay-page?" + param;
            default:
                return "forward:/pay-page?" + param;
        }
    }

    /**
     * 立即付款
     *
     * @param orderConfirmVO 订单确认信息
     * @param request        请求
     * @param response       响应
     * @throws Exception
     */
    @ApiOperation("支付宝门店下单付款")
    @PostMapping("/createAliPayOrder")
    public void createAlipayOrderForStore(OrderConfirmVO orderConfirmVO, HttpServletRequest request,
                                          HttpServletResponse response) throws Exception {
        PayOrderDTO payOrderDTO = PayOrderConvert.INSTANCE.vo2dto(orderConfirmVO);
        //获取客户端id
        payOrderDTO.setClientIp(IPUtil.getIpAddr(request));
        //保存订单
        //调用渠道代理服务
        PaymentResponseDTO<String> paymentResponseDTO = transactionService.submitOrderByAli(payOrderDTO);
        String form = paymentResponseDTO.getContent();
        //返回结果
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(form);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();

    }


}